<?php

namespace App\Http\Controllers;

use App\Http\Middleware\AccessLog;
use App\Models\ApiLogs;
use Illuminate\Http\Request;

class AccessLogController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        //
        $user_name = $request->get("user_name");
        $api_name = $request->get("api_name");
        $ip = $request->get("ip");
        $start_date = $request->get("start_date");
        $end_date = $request->get("end_date");
        $pageSize = $request->get("page_size", 10);
        $pageNum = $request->get("page_num", 1);
        $where= [] ;
        if ($user_name) {
            $where[] = ['user_name', 'like', '%' . $user_name . '%'];
        }
        if ($api_name) {
            $where[] = ['api_name', 'like', '%' . $api_name . '%'];
        }
        if ($ip) {
            $where[] = ['ip', 'like', '%' . $ip . '%'];
        }
        if ($start_date) {
            $where[] = ['created_at', '>=', $start_date . ' 00:00:00'];
        }
        if ($end_date) {
            $where[] = ['created_at', '<=', $end_date . ' 23:59:59'];
        }

        $logs = ApiLogs::where($where)->select(['id', 'user_name', 'api_name', 'method', 'request_ip as ip', 'created_at'])->orderBy('created_at', 'desc')->paginate($pageSize, ['*'], "page", $pageNum);;
        $list = $logs->getCollection();
        return Success(10100, [
            "data" => $list,
            "page_info" => [
                'current' => $logs->currentPage(), 'page_size' => (int)$pageSize, "count" => $logs->total(),
                "pages" => $logs->lastPage()
            ]
        ]);
    }


    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        if(!$id){
            return Failed(10002, ["File"=>"AccessLogController","line"=>__LINE__,"need_filed" => ['id']]);
        }
        $access_log = ApiLogs::where([["id",$id]])->first();
        if(!$access_log){
            return Failed(11101, ["File"=>"AccessLogController","line"=>__LINE__,"resource" => "not_found"]);
        }
        return Success(11100,["data"=>$access_log]);
    }


}
